import RequestMethod, {RequestMethodType} from "../../request/RequestMethod";
import ActionRoute from "./ActionRoute";
import {ActionHandleType} from "./Action";

export type ActionMapValueType = {
    // 请求方式
    method: RequestMethodType,
    // 处理方法
    handle?: ActionHandleType,
    // 转发
    forward?: string
}

class ActionMethodsBase {
    routeMap: Record<string, ActionRoute> = {}

    private _checkRoute(route: string) {
        if (this.routeMap.hasOwnProperty(route)) {
            throw new Error(`Route ${route} already exists`)
        }
    }

    /**
     * GET 请求
     * @param {string} route 路由
     * @param {ActionHandleType} handle 请求处理
     * @return {ActionMethodsBase}
     */
    get(route: string, handle: ActionHandleType): ActionMethodsBase {
        this._checkRoute(route)
        this.routeMap[route] = new ActionRoute(RequestMethod.GET, handle)
        return this
    }

    /**
     * POST 请求
     * @param {string} route 路由
     * @param {ActionHandleType} handle 请求处理
     * @return {ActionMethodsBase}
     */
    post(route: string, handle: ActionHandleType): ActionMethodsBase {
        this._checkRoute(route)
        this.routeMap[route] = new ActionRoute(RequestMethod.POST, handle)
        return this
    }

    /**
     * PUT 请求
     * @param {string} route 路由
     * @param {ActionHandleType} handle 请求处理
     * @return {ActionMethodsBase}
     */
    put(route: string, handle: ActionHandleType): ActionMethodsBase {
        this._checkRoute(route)
        this.routeMap[route] = new ActionRoute(RequestMethod.PUT, handle)
        return this
    }

    /**
     * DELETE 请求
     * @param {string} route 路由
     * @param {ActionHandleType} handle 请求处理
     * @return {ActionMethodsBase}
     */
    delete(route: string, handle: ActionHandleType): ActionMethodsBase {
        this._checkRoute(route)
        this.routeMap[route] = new ActionRoute(RequestMethod.DELETE, handle)
        return this
    }
}

export default ActionMethodsBase
